package com.raylu.day04;

import com.raylu.utils.SensorReading;
import com.raylu.utils.SensorSource;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

// 连续1s温度上升的检测
public class Example2Sensor1sTemperature {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .addSource(new SensorSource())
                .keyBy(r -> r.sensorId)
                .process(new MyProcess())
                .print();

        env.execute();
    }

    // 1 2 3 4 5 6 1 2 3
    public static class MyProcess extends KeyedProcessFunction<String, SensorReading, String> {
        // 用来保存最近一次温度
        private ValueState<Integer> lastTemp;
        // 用来保存报警定时器时间戳的状态变量
        private ValueState<Long> timerTs;
        @Override
        public void open(Configuration parameters) throws Exception {
            super.open(parameters);
            lastTemp = getRuntimeContext().getState(new ValueStateDescriptor<Integer>("last-temp", Types.INT));
            timerTs = getRuntimeContext().getState(new ValueStateDescriptor<Long>("timer", Types.LONG));
        }

        @Override
        public void processElement(SensorReading value, Context ctx, Collector<String> out) throws Exception {
            // prevTemp用来缓存最近一次的温度
            Integer prevTemp = null;
            if (lastTemp.value() != null) {
                prevTemp = lastTemp.value();
            }
            // 将当前温度更新到lastTemp
            lastTemp.update(value.temperature);

            // 如果存在报警定时器，将时间戳取出
            Long ts = null;
            if (timerTs.value() != null) {
                ts = timerTs.value();
            }

            // 防御条件，保证来的数据不是第一条数据
            if (prevTemp != null) {
                if (value.temperature < prevTemp && ts != null) {
                    // 温度下降且存在报警定时器
                    // 删除定时器
                    ctx.timerService().deleteProcessingTimeTimer(ts);
                    // 清空状态变量
                    timerTs.clear();
                } else if (value.temperature > prevTemp && ts == null) {
                    // 温度上升且没有报警定时器存在
                    long currTs = ctx.timerService().currentProcessingTime();
                    long oneSecLater = currTs + 1000L;
                    // 注册报警定时器
                    ctx.timerService().registerProcessingTimeTimer(oneSecLater);
                    // 将时间戳存下来
                    timerTs.update(oneSecLater);
                }
            }
        }

        @Override
        public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
            super.onTimer(timestamp, ctx, out);
            // 定时器用来报警
            out.collect("传感器 " + ctx.getCurrentKey() + " 连续1s温度上升！");
            timerTs.clear();
        }
    }
}
